package com.aijk.ehm.sys.service;

import com.aijk.base.entity.PagingRequest;
import com.aijk.commons.utils.Utils;
import com.aijk.ehm.sys.mapper.extra.SysRoleAuthExtMapper;
import com.aijk.ehm.sys.model.SysRoleAuthExample;
import com.aijk.ehm.sys.model.SysRoleAuth;
import com.aijk.ehm.sys.model.qo.RoleAuthQo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service()
public class SysRoleAuthService {

    private static Logger logger = LoggerFactory.getLogger(SysRoleAuthService.class);

    @Autowired
    private SysRoleAuthExtMapper mapper;


    private SysRoleAuthExample getExample(RoleAuthQo qo) {
        SysRoleAuthExample example = new SysRoleAuthExample();
        SysRoleAuthExample.Criteria criteria = example.createCriteria();
        if (qo != null ) {
            if (Utils.isNotEmpty(qo.getSortway())) example.setOrderByClause(Utils.toString(qo.getSortway()));
            if (Utils.isNotEmpty(qo.getRid())) criteria.andRidEqualTo(qo.getRid());
            if (Utils.isNotEmpty(qo.getRidList())) criteria.andRidIn(qo.getRidList());
        }

        return example;
    }

    public Integer count(RoleAuthQo qo) {
        return mapper.countByExample(getExample(qo));
    }

    public List<SysRoleAuth> find(RoleAuthQo qo) {
        return mapper.selectByExample(getExample(qo));
    }

    public PageInfo<SysRoleAuth> pageList(PagingRequest pagingRequest, RoleAuthQo qo) {
        PageHelper.startPage(pagingRequest.getPageNum(), pagingRequest.getPageSize());
        return new PageInfo<SysRoleAuth>(mapper.selectByExample(getExample(qo)));
    }
    public SysRoleAuth findOne(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    public Integer update(SysRoleAuth record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    public Integer save(SysRoleAuth record) {
        return mapper.insert(record);
    }

    public Integer delete(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }


    public void saveRoleAuth(Integer roleId, String permIds) {
        List<SysRoleAuth> auths = new ArrayList<>();
        String[] moudlesIds = permIds.split(",");
        for (String mid:moudlesIds){
            SysRoleAuth auth =new SysRoleAuth();
            auth.setRid(roleId);
            auth.setMid(Integer.parseInt(mid));
            auths.add(auth);
        }
        mapper.inserBatch(auths);
    }

    public int delRoleAuth(Integer roleId) {
        RoleAuthQo qo=new RoleAuthQo();
        qo.setRid(roleId);
        return mapper.deleteByExample(getExample(qo));
    }
}
